package com.nari.ncps.screen.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.CoalProdoperTransport;
import com.nari.ncps.screen.mapper.coal.CoalProdoperTransportMapper;
import com.nari.ncps.screen.service.coal.CoalProdoperTransportService;
import com.nari.ncps.screen.vo.coal.CoalTransportDetailVO;
import com.nari.ncps.screen.vo.coal.CoalTransportVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 生产经营煤炭运输情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalProdoperTransportServiceImpl extends ServiceImpl<CoalProdoperTransportMapper, CoalProdoperTransport> implements CoalProdoperTransportService {

    @Override
    public List<CoalTransportVO> getSalesTransport(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 构建最近6个月的年月列表
        List<CoalTransportVO> resultList = new ArrayList<>();
        
        // 查询当前年及去年的数据（可能跨年）
        List<Integer> years = new ArrayList<>();
        years.add(currentYear - 1);
        years.add(currentYear);
        
        LambdaQueryWrapper<CoalProdoperTransport> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperTransport::getYear, years);
        
        List<CoalProdoperTransport> dataList = this.list(query);
        
        // 处理数据为空的情况
        if (dataList == null || dataList.isEmpty()) {
            // 返回空数据但包含年月信息
            for (int i = 5; i >= 0; i--) {
                LocalDate monthDate = LocalDate.of(currentYear, currentMonth, 1).minusMonths(i);
                CoalTransportVO vo = new CoalTransportVO();
                vo.setYear(monthDate.getYear());
                vo.setMonth(monthDate.getMonthValue());
                vo.setRoadTransport(BigDecimal.ZERO);
                vo.setBeltTransport(BigDecimal.ZERO);
                vo.setRailTransport(BigDecimal.ZERO);
                resultList.add(vo);
            }
            return resultList;
        }
        
        // 按年月和运输类型分组汇总数据
        // Map结构: "year-month" -> transportType -> sum(transportVolume)
        Map<String, Map<Integer, BigDecimal>> monthlyData = new HashMap<>();
        
        for (CoalProdoperTransport transport : dataList) {
            if (transport.getYear() != null && transport.getMonth() != null && transport.getTransportType() != null) {
                String yearMonth = transport.getYear() + "-" + transport.getMonth();
                monthlyData.putIfAbsent(yearMonth, new HashMap<>());
                
                Map<Integer, BigDecimal> typeMap = monthlyData.get(yearMonth);
                Integer transportType = transport.getTransportType();
                
                // 汇总该年月该类型的运输量
                BigDecimal currentSum = typeMap.getOrDefault(transportType, BigDecimal.ZERO);
                if (transport.getTransportVolume() != null) {
                    typeMap.put(transportType, currentSum.add(transport.getTransportVolume()));
                }
            }
        }
        
        // 构建最近6个月的结果
        for (int i = 5; i >= 0; i--) {
            LocalDate monthDate = LocalDate.of(currentYear, currentMonth, 1).minusMonths(i);
            int queryYear = monthDate.getYear();
            int queryMonth = monthDate.getMonthValue();
            
            CoalTransportVO vo = new CoalTransportVO();
            vo.setYear(queryYear);
            vo.setMonth(queryMonth);
            
            // 获取该年月的数据
            String yearMonth = queryYear + "-" + queryMonth;
            Map<Integer, BigDecimal> typeMap = monthlyData.get(yearMonth);
            
            if (typeMap != null) {
                // 0：汽运
                vo.setRoadTransport(typeMap.getOrDefault(0, BigDecimal.ZERO));
                // 1：皮带
                vo.setBeltTransport(typeMap.getOrDefault(1, BigDecimal.ZERO));
                // 2：铁运
                vo.setRailTransport(typeMap.getOrDefault(2, BigDecimal.ZERO));
            } else {
                vo.setRoadTransport(BigDecimal.ZERO);
                vo.setBeltTransport(BigDecimal.ZERO);
                vo.setRailTransport(BigDecimal.ZERO);
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }
    
    @Override
    public CoalTransportDetailVO getTransportDetail(String orgCode) {
        CoalTransportDetailVO vo = new CoalTransportDetailVO();
        
        // 基于运输数据生成运输趋势（按日统计最近30天）
        LocalDate now = LocalDate.now();
        List<CoalTransportDetailVO.TransportTrendItem> trendData = new ArrayList<>();
        
        // 查询最近30天的日级别运输数据
        LambdaQueryWrapper<CoalProdoperTransport> query = new LambdaQueryWrapper<>();
        query.ge(CoalProdoperTransport::getYear, now.minusDays(30).getYear())
             .ge(CoalProdoperTransport::getMonth, now.minusDays(30).getMonthValue())
             .orderByAsc(CoalProdoperTransport::getYear)
             .orderByAsc(CoalProdoperTransport::getMonth);
        
        if (orgCode != null && !orgCode.isEmpty()) {
            query.eq(CoalProdoperTransport::getOrgCode, orgCode);
        }
        
        List<CoalProdoperTransport> dataList = this.list(query);
        
        // 按日期和运输类型分组
        Map<Integer, Map<Integer, BigDecimal>> dailyData = new HashMap<>();
        
        for (CoalProdoperTransport transport : dataList) {
            if (transport.getYearMonthDate() != null) {
                int day = transport.getYearMonthDate().getDate();
                dailyData.putIfAbsent(day, new HashMap<>());
                
                Map<Integer, BigDecimal> typeMap = dailyData.get(day);
                Integer transportType = transport.getTransportType();
                
                if (transportType != null && transport.getTransportVolume() != null) {
                    BigDecimal currentSum = typeMap.getOrDefault(transportType, BigDecimal.ZERO);
                    typeMap.put(transportType, currentSum.add(transport.getTransportVolume()));
                }
            }
        }
        
        // 生成趋势数据
        for (Map.Entry<Integer, Map<Integer, BigDecimal>> entry : dailyData.entrySet()) {
            CoalTransportDetailVO.TransportTrendItem item = new CoalTransportDetailVO.TransportTrendItem();
            item.setDay(entry.getKey());
            
            Map<Integer, BigDecimal> typeMap = entry.getValue();
            item.setTruckTransport(typeMap.getOrDefault(0, BigDecimal.ZERO));
            item.setBeltTransport(typeMap.getOrDefault(1, BigDecimal.ZERO));
            item.setRailTransport(typeMap.getOrDefault(2, BigDecimal.ZERO));
            
            trendData.add(item);
        }
        
        vo.setTrendData(trendData);
        
        // 注：按热值分类的运输量需要专门的数据表支持，目前设置为零
        vo.setLowHeatTransport(BigDecimal.ZERO);
        vo.setNormalHeatTransport(BigDecimal.ZERO);
        vo.setStandardHeatTransport(BigDecimal.ZERO);
        vo.setPremiumHeatTransport(BigDecimal.ZERO);
        
        return vo;
    }
}
